import 'dart:developer';

import 'package:manager/exts/route_ext.dart';
import 'package:manager/exts/storage_ext.dart';
import 'package:bot_toast/bot_toast.dart';
import 'package:common_ui/common_ui.dart';
import 'package:common_ui/components/exts/widgets_ext.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:manager/configs/theme_data.dart';
import 'package:manager/res/color.dart';
import 'package:manager/services/plugin_service.dart';
import 'package:manager/widgets/widgets_ext.dart';
import 'package:logger/logger.dart';
import 'package:url_launcher/url_launcher_string.dart';

import '../configs/app_data.dart';
import '../configs/sp_key.dart';
import '../exts/string_ext.dart';

void logout(){
  AppData.userId = '';
  saveData(SpKey.user_id, '');
  saveData(SpKey.user_info, null);
  // toLogin();
}
hideSoftKeyboard() {
  FocusScope.of(Get.context!).requestFocus(FocusNode());
}

///屏幕宽度
double screenWide() {
  return Get.width;
}

///屏幕高度
double screenHeight() {
  return Get.height;
}

///带有返回数据的通讯方法
Future<T> sendToNativeWithResult<T>(String method, {dynamic args}) async {
  return await Get.find<PluginService>().invokeMethod(method, args: args);
}

void sendToNative(String method, {dynamic args}) async {
  await Get.find<PluginService>().invokeMethod<void>(method, args: args);
}

///拨打电话
void callPhone(String? phone) {
  if (phone.isNullEmpty()) {
    showToast('电话号码不正确');
  } else {
    launchUrlString('tel:$phone');
    showLog(phone.toString());
  }
}

///普通的dialog
void showCommonDialog(String notify,
    {String? cancelText,
    String? confirmText,
    String? title,
    bool? barrierDismissible,
    bool? showCancel,
    VoidCallback? onCancel,
    VoidCallback? onConfirm}) {
  showDialog(
      context: Get.context!,
      barrierDismissible: barrierDismissible ?? true,
      builder: (context) {
        return Dialog(
          backgroundColor: Colors.black12.withAlpha(100),
          child: Wrap(
            children: [
              Container(
                padding: const EdgeInsets.only(top: 16),
                width: Get.width * 0.8,
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(8)),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    title == null
                        ? Container()
                        : Container(
                            padding: const EdgeInsets.only(
                                left: 16, right: 16, bottom: 12),
                            child: Text(
                              title,
                              style: const TextStyle(
                                  fontSize: 18, color: Colors.black87),
                            ),
                          ),
                    Text(
                      notify,
                      style: Styles.textCommon,
                      softWrap: true,
                    ).marginOnly(left: 12, right: 12),
                    horizonLine(
                        color: ColorPool.line_color,
                        height: 1,
                        margin: const EdgeInsets.only(top: 24)),
                    Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        (showCancel ?? true)
                            ? Expanded(
                                child: textBgButton(() {
                                onCancel?.call();
                                Get.back();
                              }, cancelText ?? '取消',
                                    style: Styles.textMedium,
                                    bgColor: Colors.white,
                                    padding: const EdgeInsets.only(
                                        top: 12, bottom: 12),
                                    radius: 8))
                            : Container(),
                        (showCancel ?? true)
                            ? verticalLine(color: ColorPool.line_color, wide: 1)
                            : Container(),
                        Expanded(
                            child: textBgButton(() {
                          Get.back();
                          onConfirm?.call();
                        }, confirmText ?? '确定',
                                bgColor: Colors.white,
                                radius: 8,
                                padding:
                                    const EdgeInsets.only(top: 12, bottom: 12),
                                style: const TextStyle(
                                    color: ColorPool.theme_color,
                                    fontSize: 14)))
                      ],
                    )
                  ],
                ),
              )
            ],
          ),
        );
      });
}

///普通的dialog
void showCustomDialog(Widget notify,
    {String? cancelText,
    String? confirmText,
    String? title,
    bool? barrierDismissible,
    bool? confirmDismissible,
    bool? showCancel,
    VoidCallback? onCancel,
    VoidCallback? onConfirm,
    double? wideScale}) {
  showDialog(
      context: Get.context!,
      barrierDismissible: barrierDismissible ?? true,
      builder: (context) {
        return Dialog(
          backgroundColor: Colors.black12.withAlpha(100),
          child: Wrap(
            children: [
              Container(
                padding: const EdgeInsets.only(top: 8),
                width: Get.width * (wideScale ?? 0.8),
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(8)),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    title == null
                        ? Container()
                        : Container(
                            padding: const EdgeInsets.only(
                                left: 16, right: 16, bottom: 12),
                            child: Text(
                              title,
                              style: const TextStyle(
                                  fontSize: 18, color: Colors.black87),
                            ),
                          ),
                    Container(
                      child: notify,
                    ),
                    horizonLine(
                        color: ColorPool.line_color,
                        height: 1,
                        margin: const EdgeInsets.only(top: 24)),
                    Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        (showCancel ?? true)
                            ? Expanded(
                                child: textBgButton(() {
                                onCancel?.call();
                                Get.back();
                              }, cancelText ?? '取消',
                                    style: Styles.textMedium,
                                    bgColor: Colors.white,
                                    padding: const EdgeInsets.only(
                                        top: 12, bottom: 12),
                                    radius: 8))
                            : Container(),
                        (showCancel ?? true)
                            ? verticalLine(color: ColorPool.line_color, wide: 1)
                            : Container(),
                        Expanded(
                            child: textBgButton(() {
                          if (confirmDismissible ?? true) {
                            Get.back();
                          }

                          onConfirm?.call();
                        }, confirmText ?? '确定',
                                bgColor: Colors.white,
                                radius: 8,
                                padding:
                                    const EdgeInsets.only(top: 12, bottom: 12),
                                style: const TextStyle(
                                    color: ColorPool.theme_color,
                                    fontSize: 14)))
                      ],
                    )
                  ],
                ),
              )
            ],
          ),
        );
      });
}

///普通带有确定取消按钮的信息提示框
void showNotifyDialog(String notify,
    {VoidCallback? onConfirm,
    VoidCallback? onCancel,
    bool? barrierDismissible}) {
  showDialog(
      context: Get.context!,
      barrierDismissible: barrierDismissible ?? false,
      builder: (context) {
        return AlertDialog(
          contentPadding: const EdgeInsets.fromLTRB(12, 24, 12, 16),
          content: Text(
            notify,
            style: Styles.textCommon,
            softWrap: true,
            maxLines: 6,
          ),
          actions: [
            TextButton(
              onPressed: () {
                Get.back();
                onCancel?.call();
              },
              child: const Text('取消'),
            ),
            TextButton(
              onPressed: () {
                Get.back();
                onConfirm?.call();
              },
              child: const Text('确定'),
            ),
          ],
        );
      });
}

///普通带有输入框弹窗
void showEditDialog(String hint,
    {Function(String)? onConfirm,
    VoidCallback? onCancel,
    bool? barrierDismissible}) {
  String? content;
  showDialog(
      context: Get.context!,
      barrierDismissible: barrierDismissible ?? false,
      builder: (context) {
        return AlertDialog(
          contentPadding: const EdgeInsets.fromLTRB(12, 24, 12, 16),
          content: Container(
            width: double.infinity,
            height: 80,
            constraints: const BoxConstraints(minHeight: 40, maxHeight: 80),
            alignment: Alignment.center,
            child: TextField(
              onChanged: (v) => content = v,
              decoration: InputDecoration(
                  hintText: hint,
                  contentPadding: const EdgeInsets.fromLTRB(12, 3, 12, 3),
                  border: const OutlineInputBorder(
                      borderSide: BorderSide(color: ColorPool.line_color))),
              maxLines: 4,
              minLines: 1,
              style: Styles.textCommon,
            ),
          ),
          actions: [
            TextButton(
              onPressed: () {
                onCancel?.call();
                Get.back();
              },
              child: const Text('取消'),
            ),
            TextButton(
              onPressed: () {
                if (content.isNullEmpty()) {
                  showToast('请输入内容');
                  return;
                }
                onConfirm?.call(content!);
                Get.back();
              },
              child: const Text('确定'),
            ),
          ],
        );
      });
}

///普通带有标题输入框弹窗
void showTitleEditDialog(String hint, String title,
    {Function(String)? onConfirm,
    VoidCallback? onCancel,
    bool? barrierDismissible}) {
  String? content;
  showDialog(
      context: Get.context!,
      barrierDismissible: barrierDismissible ?? false,
      builder: (context) {
        return AlertDialog(
          contentPadding: const EdgeInsets.fromLTRB(12, 16, 12, 6),
          content: Container(
              width: double.infinity,
              height: 90,
              constraints: const BoxConstraints(minHeight: 40, maxHeight: 90),
              alignment: Alignment.center,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  SingleText(
                    title,
                    textStyle: const TextStyle(
                        fontSize: 18, color: ColorPool.text_common),
                    margin: const EdgeInsets.only(bottom: 8),
                  ),
                  TextField(
                    onChanged: (v) => content = v,
                    decoration: InputDecoration(
                        hintText: hint,
                        contentPadding: const EdgeInsets.fromLTRB(12, 3, 12, 3),
                        border: const OutlineInputBorder(
                            borderSide:
                                BorderSide(color: ColorPool.line_color))),
                    maxLines: 4,
                    minLines: 1,
                    style: Styles.textCommon,
                  ),
                ],
              )),
          actions: [
            TextButton(
              onPressed: () {
                onCancel?.call();
                Get.back();
              },
              child: const Text('取消'),
            ),
            TextButton(
              onPressed: () {
                if (content.isNullEmpty()) {
                  showToast('请输入内容');
                  return;
                }
                Get.back();
                onConfirm?.call(content!);
              },
              child: const Text('确定'),
            ),
          ],
        );
      });
}

///关闭软键盘
void closeInput() {
  FocusScope.of(Get.context!).requestFocus(FocusNode());
}

void showToast(String text, {int duration = 3}) {
  BotToast.showText(text: text, duration: Duration(seconds: duration));
}

void showSnackBar(String title, String message,
    {int dura = 3, SnackPosition? snackPosition}) {
  Get.snackbar(title, message,
      snackPosition: snackPosition,
      isDismissible: true,
      duration: Duration(seconds: dura));
}

///从相册选择图片
Future<String?> selectPhotoFromGallery() async {
  return await Get.find<PluginService>().selectPhoto();
}

///使用相机拍摄图片
Future<String?> takePhoto() async {
  return await Get.find<PluginService>().takePhoto();
}

///请求焦点
void requestFocus(FocusNode node) {
  FocusScope.of(Get.context!).requestFocus(node);
}

///自定义加载动画
void showLoading(String? notify) {
  BotToast.showCustomLoading(
      clickClose: true,
      allowClick: false,
      backgroundColor: Colors.transparent,
      onClose: () {},
      toastBuilder: (cancel) => Container(
            width: 120,
            padding: const EdgeInsets.only(top: 12, bottom: 12),
            alignment: Alignment.center,
            height: 120,
            decoration: BoxDecoration(
                color: Colors.black54, borderRadius: BorderRadius.circular(8)),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                const CircularProgressIndicator(),
                Text(
                  notify ?? '加载中...',
                  style: const TextStyle(color: Colors.white, fontSize: 12),
                )
              ],
            ),
          ));
}

void cancelLoading() {
  BotToast.closeAllLoading();
}

Logger? logger;

///统一log管理,release版本不做log输出
///使用Logger打印内容,可以追踪 到log的位置,便于查找错误位置
void loggerMsg(dynamic msg) {
  if (kDebugMode) {
    logger ??= Logger(printer: PrettyPrinter(printTime: true));
    logger!.i(msg);
  }
}

///统一log管理,release版本不做log输出
///log内容简洁,便于打印json数据
void showLog(dynamic msg) {
  if (kDebugMode) {
    log(msg.toString());
  }
}
